<template>
	<div>
		<game-box>
			<template #config>
				<div class="h-full w-full bg-[#2a364f] px-[12px] py-[16px]">
					<BetAmount
						v-if="!isDesktop"
						:type="type"
						:isRuning="isRuning"
						:isDisabled="isDisabled"
						:showMax="maxbet"
						:amount="amount"
						@changeMoneyDisabled="changeMoneyDisabled"
						@changeAmount="changeAmount" />
					<StartBtn
						v-if="!isDesktop"
						@handleClick="handleStart"
						:type="type"
						stopIcon="dice"
						:isRuning="isRuning"
						:stoping="stoping"
						:isDisabled="isMoneyDisabled || isDisabled" />
					<SwitchTab
						v-if="isDesktop"
						:class="!isDesktop ? 'mt-4' : ''"
						:type="type"
						:isRuning="isRuning"
						:isDisabled="isDisabled"
						@changeMode="changeMode" />
					<div class="h-group-t"></div>
					<BetAmount
						v-if="isDesktop"
						:type="type"
						:isRuning="isRuning"
						:isDisabled="isDisabled"
						:showMax="maxbet"
						:amount="amount"
						@changeMoneyDisabled="changeMoneyDisabled"
						@changeAmount="changeAmount" />
					<div class="h-group-t" v-if="isDesktop"></div>
					<template v-if="type === 'auto'">
						<LoopCount
							@changeLoop="changeLoop"
							:type="type"
							:loopNum="loopNum"
							:isRuning="isRuning"
							:isDisabled="isDisabled" />
						<div class="h-group-t"></div>
						<profit-percentage
							:isRuning="isRuning"
							:title="$t('miniGames.onwin')"
							:isDisabled="isDisabled"
							type="profitPer"
							@change="changeProfitPercentage" />
						<div class="h-group-t"></div>
						<profit-percentage
							:isRuning="isRuning"
							:isDisabled="isDisabled"
							:title="$t('miniGames.onloss')"
							type="lossPer"
							@change="changeLossPercentage" />
						<div class="h-group-t"></div>
						<stop-profitable
							@changeProfitable="changeProfitable"
							:isRuning="isRuning"
							:isDisabled="isDisabled" />
						<div class="h-group-t"></div>
						<loss-suspension
							@changeLoss="changeLoss"
							:isRuning="isRuning"
							:isDisabled="isDisabled" />
					</template>
					<div v-if="type === 'manual'">
						<div class="yingli">
							<span class="yingli1 text-[14px]">{{ $t('miniGames.profit') }}</span>
							<span class="yingli2 text-[12px]">
								<base-amount :value="value" :currency="currency" hide-currency reverse-fiat />
							</span>
						</div>
						<n-input
							size="large"
							class="flex-1 h-[40px] mt-[4px] bg-[#3e4c68] input-style rounded-[4px]"
							:disabled="isDisabled"
							v-model:value="value"
							readonly
							:on-input="changeAmount"
							:on-focus="handleSelect"
							ref="inputInstRef">
							<template #suffix>
								<base-currency-fait />
							</template>
						</n-input>
					</div>
					<div v-if="isDesktop">
						<StartBtn
							:type="type"
							:isRuning="isRuning"
							:stoping="stoping"
							stopIcon="dice"
							:isDisabled="isMoneyDisabled || isDisabled"
							@handleClick="handleStart" />
						<div class="h-group-t"></div>
					</div>
					<SwitchTab
						v-if="!isDesktop"
						:class="!isDesktop ? 'mt-4' : ''"
						:type="type"
						:isRuning="isRuning"
						:isDisabled="isDisabled"
						@changeMode="changeMode" />
				</div>
			</template>
			<template #content>
				<div ref="gameContent" class="h-full w-full bg-[#1B2538]"></div>
			</template>
		</game-box>
		<result-dialog
			:showDialog="showResult"
			:betId="resultBetId"
			gameType="dice"
			:gameObj="mDiceGame"
			@close="closeResultDialog" />
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import GameBox from '../components/game-box/index.vue'
import StartBtn from '../components/common/start-button.vue'
import BetAmount from '../components/common/bet-amount.vue'
import SwitchTab from '../components/common/switch-tab.vue'
import LoopCount from '../components/common/loop-count.vue'
import stopProfitable from '../components/common/stop-profitable.vue'
import lossSuspension from '../components/common/loss-suspension.vue'
import profitPercentage from '../components/common/profit-percentage.vue'
import ResultDialog from '../components/dialog/result.vue'
import { loadJs, getCurrencyIcon } from '@/utils'
import { isDesktop } from '@/hooks'
import { playDice, gameEndSettled } from '@/api/third/mini-games'
import { useWalletStore, useAccountStore, useAppStore } from '@/store'
import { AccountShowType } from '@/types'
// import { THIRD_GAME } from '@/constants/global-key'
import { eventBus } from '@/views/games/eventBus'
import { BaseAmount, BaseCurrencyFait } from '@/components/base'
import { NInput } from 'naive-ui'
import { showError, message } from '@/utils'
import { qlaunchUrl } from '../getUrlT'
import {
	transferToNumber,
	transformationAmount,
	getDecimalPlaces,
	calculateProfitLoss
} from '../util'
import { delayGameTime, accelerateTimeInter, delayTimeInter } from '@/views/games/config'
import type { InputInst } from 'naive-ui'

const accountStore = useAccountStore()
// import { getBalance } from '@/api/wallet.ts'
const walletStore = useWalletStore()
const currency = computed(() => walletStore.balanceCur?.currency)
const value = ref('0')
const type = ref('manual')
const isRuning = ref(false)
const isDisabled = ref(true)
const isMoneyDisabled = ref(false)
const stoping = ref(false)

const gameContent = ref(null)
let mDiceGame: any = null
const loopNum = ref(0)
const profit = ref<string | number>(0)
const loss = ref<string | number>(0)
const amount = ref<string | number>(0)
const autoOneAmount = ref<string | number>(0)
const profitPer = ref<any>({ value: 0, active: 'rest' })
const lossPer = ref<any>({ value: 0, active: 'rest' })
const maxbet = ref(false)
const mute = ref(false)
const rocket = ref(false)
const timeInter = ref(delayTimeInter)
const showResult = ref(false)
const resultBetId = ref('')
const inputInstRef = ref<InputInst | null>(null)
const appStore = useAppStore()

let nowTarget = 50.5
//当前买大买小
let buyBigOrSmall = true
//数据错误状态
let errorState = false
let languageMap: any = null

let interval: any = null
// 累计盈利亏损
const profitLossTotal = ref(0)
// 游戏返回数据
let gameBackData: any = {}

watch(
	() => accountStore.token,
	() => qlaunchUrl()
)
watch(
	() => appStore.lang,
	(val: string) => {
		mDiceGame?.setLanguage(languageMap?.[val])
	}
)
// watch(
// 	() => walletStore.balanceCur?.currency,
// 	() => {
// 		mDiceGame?.setCurrency(getCurrencyIcon())
// 	}
// )
onMounted(() => {
	qlaunchUrl()
	initGame()
	eventBus.on('changeRocket', (val: any) => {
		console.log(val)
		rocket.value = val
		mDiceGame?.setSpeedUpMode(val)
		timeInter.value = val ? accelerateTimeInter : delayTimeInter
	})

	eventBus.on('changeMaxBet', (val: any) => {
		console.log(val)
		maxbet.value = val
	})
	eventBus.on('changeMute', (val: boolean) => {
		console.log(val)
		mute.value = val
		mDiceGame.setSoundEffect(!val)
	})
})
onUnmounted(() => {
	restTimeAuto()
	// 在组件卸载时移除监听器
	eventBus.off('changeRocket', () => {
		// 空的回调函数
	})
	eventBus.off('changeMaxBet', () => {
		// 空的回调函数
	})
	eventBus.off('changeMute', () => {
		// 空的回调函数
	})
})
const changeMoneyDisabled = (status: boolean) => {
	isMoneyDisabled.value = status
}
const restTimeAuto = (auto = false) => {
	interval && clearTimeout(interval)
	isRuning.value = false
	isDisabled.value = false
	if (auto) {
		message.success('自动投注完成', { duration: 5000 })
	}
}
const handleSelect = () => {
	inputInstRef.value?.select()
}
const gameEnd = async () => {
	if (!gameBackData?.id) return
	await gameEndSettled({
		round: gameBackData?.id
	})
	gameBackData = {}
}
const initGame = () => {
	loadJs('/gameLib.js').then((originalGameLib: any) => {
		let Language = originalGameLib.Language
		languageMap = {
			zh: Language.ZH,
			zhTW: Language.zhTW,
			en: Language.EN
		}
		mDiceGame = new originalGameLib.DiceGame({
			parentElement: gameContent.value,
			language: languageMap[appStore.lang],
			currencyIcon: getCurrencyIcon(),
			backgroundColor: 'rgba(0, 0, 0, 0)',
			backgroundOpacity: 0,
			buyBigOrSmall: true,
			soundEffect: true,
			onGameEnd: () => {
				//游戏状态
				console.log('游戏结束')
				if (type.value !== 'auto') {
					isDisabled.value = false
				}
				gameEnd()
				// walletStore.getBalance(0)
			},
			onGameResultSquareClick: (diceGameResult: any) => {
				// 点击结果
				resultBetId.value = diceGameResult.betId
				showResult.value = true
			},
			onGameInputTypeChange: (_value: any, _buyBigOrSmall: any) => {
				//改变输入类型
				console.log('当前目标' + _value + '买大小' + _buyBigOrSmall)
				nowTarget = Number(_value)
				buyBigOrSmall = _buyBigOrSmall
				calculateProfit()
			},
			onGameInputTypeError: (_errorState: any) => {
				// console.log(_errorState)
				errorState = _errorState
				if (_errorState) {
					isDisabled.value = true
				} else {
					isDisabled.value = false
				}
			},
			onGameLoadEnd: () => {
				//游戏加载完成
				isDisabled.value = false
			}
		})
		const div = gameContent.value as unknown as HTMLElement
		const child = mDiceGame?.render()
		if (!div.contains(child)) {
			div?.appendChild(child)
		}
		calculateProfit()
	})
}
// 计算盈利
const calculateProfit = () => {
	const multiplier = mDiceGame?.getMultiplier() || 0
	const nAmount = Number(amount.value)
	const profit = (nAmount * Number(multiplier) - nAmount).toFixed(getDecimalPlaces())
	value.value = transferToNumber(profit)
}
const closeResultDialog = () => {
	showResult.value = false
}
const handleStart = async () => {
	profitLossTotal.value = 0
	if (errorState) {
		return
	}
	if (type.value === 'auto') {
		console.log('auto')
		if (isRuning.value) {
			stoping.value = true
			setTimeout(() => {
				stoping.value = false
				restTimeAuto(true)
			}, delayGameTime)
		} else {
			message.success('自动投注开始', { duration: 5000 })
			isRuning.value = true
			autoOneAmount.value = amount.value

			if (loopNum.value === 0) {
				playGame('all')
			}
			if (loopNum.value > 0) {
				playGame()
				loopNum.value--
				if (loopNum.value === 0) {
					isRuning.value = false
					interval && clearTimeout(interval)
					message.success('自动投注完成', { duration: 5000 })
				}
			}
		}
	} else {
		isRuning.value = true
		console.log('开始')
		await playGame()
		isRuning.value = false
	}
}

const playGame = async (loop: string = '') => {
	//没有token情况下
	if (!accountStore.token) {
		accountStore.showAccount(AccountShowType.login)
		return
	}
	try {
		if (stoping.value) return
		//开始游戏
		mDiceGame.startGame()
		const { data } = await playDice({
			amount: transformationAmount(amount.value),
			currency: walletStore.balanceCur?.currency,
			identifier: 'dice',
			condition: buyBigOrSmall ? 'above' : 'below',
			target: nowTarget
		})
		gameBackData = data
		// gameStatus = true;
		//获取游戏结果
		// 下注
		if (buyBigOrSmall) {
			if (data.state.result >= nowTarget) {
				mDiceGame.addGameResult(data.id, data.state.result, true)
			} else {
				mDiceGame.addGameResult(data.id, data.state.result, false)
			}
		} else {
			if (data.state.result <= nowTarget) {
				mDiceGame.addGameResult(data.id, data.state.result, true)
			} else {
				mDiceGame.addGameResult(data.id, data.state.result, false)
			}
		}
		// 计算是否达到盈亏阈值
		if (
			calculateProfitLoss(data, {
				type,
				amount,
				profitPer,
				lossPer,
				profit,
				loss,
				profitLossTotal,
				autoOneAmount
			})
		) {
			restTimeAuto()
			return
		}
		// 自动投注状态
		if (loop === 'all' && isRuning.value) {
			interval = setTimeout(() => {
				playGame(loop)
			}, timeInter.value)
		}
		if (loopNum.value > 0 && isRuning.value) {
			interval = setTimeout(() => {
				playGame()
				loopNum.value--
				if (loopNum.value <= 0) {
					restTimeAuto(true)
				}
			}, timeInter.value)
		}
	} catch (error: any) {
		showError(error)
		interval && clearTimeout(interval)
		isDisabled.value = false
		isRuning.value = false
	}
}

const changeLoop = (val: string) => {
	loopNum.value = parseInt(val)
}
const changeProfitable = (val: string) => {
	console.log(val, 'profit')
	profit.value = val
}
const changeProfitPercentage = (data: any) => {
	profitPer.value = data
}
const changeLossPercentage = (data: any) => {
	lossPer.value = data
}
const changeLoss = (val: string) => {
	console.log(val, 'loss')
	loss.value = val
}
const changeAmount = (val: string) => {
	console.log(val, 'amount')
	amount.value = val
	calculateProfit()
}
const changeMode = (val: string) => {
	type.value = val
}
</script>
<style lang="scss" scoped>
.yingli {
	display: flex;
	justify-content: space-between;
	height: 18px;
}
.yingli1,
.yingli2 {
	color: var(--text-396-a-5-aa, #96a5aa);
	text-align: right;
	font-style: normal;
	font-weight: 600;
	line-height: 18px; /* 150% */
}
.input-style {
	box-shadow:
		0 1px 3px 0 rgba(0, 0, 0, 0.2),
		0 1px 2px 0 rgba(0, 0, 0, 0.12);
	:deep(.n-input__input > .n-input__input-el) {
		height: 100% !important;
	}
}
.h-group-t {
	height: 12px;
}
</style>
